<template>
	<div class="container add_edit">
		<el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
			<el-form-item label="标题">
				<el-input v-model="form.title" placeholder="请输入标题" clearable></el-input>
			</el-form-item>
			<el-form-item label="比例">
				<el-input v-model="form.proportion" type="number" placeholder="请输入比例(1代表百分之1)" clearable></el-input>
			</el-form-item>
			<el-button :loading="formLoading" round icon="el-icon-check" class="confirm-btn"
				@click="submitForm('ruleForm')">提交</el-button>
			<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
		</el-form>
	</div>
</template>

<script>
	const __name = 'wmz-proportion';
	export default {
		data() {
			return {
				dataId: '',
				formLoading: false,
				form: {
					title: '',
					proportion: ''
				},
				rules: {}
			};
		},
		methods: {
			async loadData() {
				if (!this.dataId) {
					this.$db[__name].getsort().then(res => {
						if (res.code == 200) {
							this.form.sort = ++res.datas.sort;
						}
					});
					return;
				}

				await this.$db[__name].tofirst(this.dataId).then(res => {
					if (res.code == 200) {
						for (let item in this.form) {
							this.form[item] = res.datas[item];
						}
					}
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.formLoading = true;
						if (!this.dataId) {
							this.$db[__name].add(this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						} else {
							this.$db[__name].update(this.dataId, this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						}
					}
				});
			},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/goods/proportion/proportion'
				});
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
		}
	};
</script>

<style></style>